package cate.game.activity.convertfairy;

import cate.common.table.activity.fairyreplace.row.FairyReplaceBaseRow;
import cate.common.table.item.fairy.row.FairyBaseRow;
import cate.common.util.GameResult;
import cate.game.activity.base.core.RoleActivitySingle;
import cate.game.activity.convertfairy.msg.ConvertFairyActivityInfoResp;
import cate.game.res.MixRes;
import cate.game.res.MixResItem;
import cate.game.role.bag.fairy.Fairy;
import cate.game.train.fairy.msg.FairyLevelUpResp;

import java.util.List;
import java.util.stream.Collectors;

public class ConvertFairyActivity extends RoleActivitySingle {

    public GameResult<ConvertFairyActivity> convert(String from, int to) {
        GameResult<ConvertFairyActivity> r = new GameResult<>();
        r.data = this;
        FairyReplaceBaseRow baseRow = getBaseRow();
        if (baseRow == null) {
            return r.fail("活动不存在");
        }
        Fairy fairy = role.getBag().getFairy().getItem(from);
        if (fairy == null) {
            return r.fail("用于置换的灵器不存在背包");
        }
        if (fairy.tid == to) {
            return r.fail("无法置换相同的灵器");
        }
        FairyBaseRow fairyBaseRow = role.getGame().table.fairy.base.get(to);
        if (fairyBaseRow == null) {
            return r.fail("目标灵器不存在");
        }
        if (fairy.getTpl(role.getGame()).level != fairyBaseRow.level) {
            return r.fail("只能兑换等级相同的灵器");
        }
        if (!containsFairy(to)) {
            return r.fail("本期活动不包含目标灵器");
        }
        //消耗物品
        MixRes cost = new MixRes(baseRow.cost);
        GameResult<MixResItem> consume = cost.consume(role);
        if (!consume.ok()) {
            return r.fail(consume);
        }
        fairy.tid = to;
        role.sendNow(new FairyLevelUpResp(fairy, null, (byte) 0));
        return r;
    }

    @Override
    public void onRoleOpen() {

    }

    @Override
    public void onRoleEnd() {

    }

    @Override
    public void initSend() {
        noticeUpdate();
    }

    @Override
    public void excelCheck() {

    }

    public void noticeUpdate() {
        role.sendNow(new ConvertFairyActivityInfoResp(this));
    }

    private FairyReplaceBaseRow getBaseRow() {
        return role.getGame().table.fairyReplace.base.get(activityId());
    }

    private boolean containsFairy(int tid) {
        if (getBaseRow() == null) {
            return false;
        }
        List<Integer> list = role.getGame().table.fairyReplace.group.list.stream().filter(row->row.fairyGroup==getBaseRow().replaceGroup).map(row->row.fairyTid).collect(Collectors.toList());
        return list.contains(tid);
    }
}
